package com.cookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/**
		 * 1.他是request方法，如果请求信息中有传送了用于存放sessionID的Cookie(perharps other method...encodeURL)
		 * 该方法就会根据这个SessionID在服务器中查找对应的session对象。并返回(引用地址)
		 * 如果请求没有传送用于存放SessionID的Cookie,或者传过来的SessionID在服务器中找不到对应的Session
		 * 对象，则创建一个新的Session对象，并且生成的响应中通过Cookie的方式送回这个生成的SessionID
		 * 
		 */

		HttpSession session = request.getSession();
		/**写了这个Cookie 给他自己的替换了,JSEESIONID是tomcat创建的名*/
		Cookie cookie = new Cookie("JSEESIONID", session.getId());
		cookie.setMaxAge(60 * 60);
		response.addCookie(cookie);
		
		Integer ant = (Integer) session.getAttribute("count_key");
		if (ant == null) {
			ant = 0;
		}
		ant++;
		session.setAttribute("count_key", ant);

		/** The tomcat default value is an hour half past. */
		session.setMaxInactiveInterval(5);

		/** 一调这个方法就将session关掉了*/
		// session.invalidate();
		
		PrintWriter out = response.getWriter();
	
		out.println("<HTML>");
		out.println("<HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("<BODY>");
		out.println("<h1>"+ant+"</h1>");
		out.println("</BODY>");
		out.println("</HTML>");
		out.close();
	}

}
